package Math;

/**
 * @Classname JZ43整数中1出现的次数
 * @Description TODO
 * @Date 2023/3/7 20:55
 * @Created by xjl
 */
public class JZ43整数中1出现的次数 {
    /**
     * @description 整数中1出现的次数
     * @param: n
     * @date: 2023/3/7 20:56
     * @return: int
     * @author: xjl
     */
    public int countDigitOne(int n) {
        int digit = 1, res = 0;
        int high = n / 10, cur = n % 10, low = 0;
        while (high != 0 || cur != 0) {
            if (cur == 0) {
                res += high * digit;
            } else if (cur == 1) {
                res += high * digit + low + 1;
            } else {
                res += (high + 1) * digit;
            }
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;
    }

    /**
     * @description 相当于的暴力求解的顺序
      * @param: n
     * @date: 2023/3/7 21:15
     * @return: int
     * @author: xjl
    */
    public int countDigitOne2(int n) {
        String result = "";
        for (int i = 1; i <= n; i++) {
            result += String.valueOf(i);
        }
        int count = 0;
        for (int i = 0; i < result.length(); i++) {
            if (result.charAt(i) == '1') {
                count++;
            }
        }
        return count;
    }
}
